package com.hl.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.hl.common.result.R;
import com.hl.common.result.ResponseEnum;
import com.hl.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 朱炫达
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    public void setRedisTemplate(RedisTemplate<String,String> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uuidToken = request.getHeader("Authorization");
        if (uuidToken==null || uuidToken.equals("") || !JwtUtils.checkToken(uuidToken)){
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(R.setResult(ResponseEnum.LOGIN_AUTHORIZATION_ERROR)));
            return false;
        }

        String userToken = redisTemplate.opsForValue().get(JwtUtils.getUUIDByJwtToken(uuidToken));
        if (userToken==null || userToken.equals("") || !JwtUtils.checkToken(userToken)){
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(R.setResult(ResponseEnum.LOGIN_AUTHORIZATION_ERROR)));
            return false;
        }

        return true;
    }
}
